/**
 * Task 系统性能测试
 * 
 * 用于验证性能优化效果
 * 
 * @author AI Assistant
 * @date 2025-11-30
 */

import task from './task';
import { Log } from '../logger/LoggerGlobal';

/**
 * 性能测试工具
 */
class PerformanceTest {
    /**
     * 测试顺序任务性能
     */
    public static async testSyncPerformance(taskCount: number = 1000): Promise<void> {
        Log.info(`\n========== 测试 Sync 性能 (${taskCount} 个任务) ==========`);

        // 测试 1: 不带进度回调
        const startTime1 = performance.now();
        await new Promise<void>((resolve) => {
            const sync1 = task.createSync();
            for (let i = 0; i < taskCount; i++) {
                sync1.add((next) => next(i));
            }
            sync1.start(() => {
                const endTime1 = performance.now();
                Log.info(`不带进度回调: ${(endTime1 - startTime1).toFixed(2)}ms`);
                resolve();
            });
        });

        // 测试 2: 带进度回调
        const startTime2 = performance.now();
        await new Promise<void>((resolve) => {
            const sync2 = task.createSync();
            for (let i = 0; i < taskCount; i++) {
                sync2.add((next) => next(i));
            }
            sync2.start(() => {
                const endTime2 = performance.now();
                Log.info(`带进度回调: ${(endTime2 - startTime2).toFixed(2)}ms`);
                resolve();
            }, {
                onProgress: (current, total, percentage) => {
                    // 模拟进度更新
                }
            });
        });

        // 测试 3: 内存占用
        const sync3 = task.createSync();
        for (let i = 0; i < taskCount; i++) {
            sync3.add((next) => next({ index: i, data: new Array(100).fill(i) }));
        }
        
        const memBefore = (performance as any).memory?.usedJSHeapSize || 0;
        await new Promise<void>((resolve) => {
            sync3.start(() => {
                const memAfter = (performance as any).memory?.usedJSHeapSize || 0;
                const memUsed = ((memAfter - memBefore) / 1024 / 1024).toFixed(2);
                Log.info(`内存占用: ${memUsed}MB`);
                
                // 清理
                sync3.dispose();
                resolve();
            });
        });
    }

    /**
     * 测试并行任务性能
     */
    public static async testASyncPerformance(taskCount: number = 1000): Promise<void> {
        Log.info(`\n========== 测试 ASync 性能 (${taskCount} 个任务) ==========`);

        // 测试 1: 不带进度回调
        const startTime1 = performance.now();
        await new Promise<void>((resolve) => {
            const async1 = task.createASync();
            for (let i = 0; i < taskCount; i++) {
                async1.add((next) => next(i));
            }
            async1.start(() => {
                const endTime1 = performance.now();
                Log.info(`不带进度回调: ${(endTime1 - startTime1).toFixed(2)}ms`);
                resolve();
            });
        });

        // 测试 2: 带进度回调
        const startTime2 = performance.now();
        await new Promise<void>((resolve) => {
            const async2 = task.createASync();
            for (let i = 0; i < taskCount; i++) {
                async2.add((next) => next(i));
            }
            async2.start(() => {
                const endTime2 = performance.now();
                Log.info(`带进度回调: ${(endTime2 - startTime2).toFixed(2)}ms`);
                resolve();
            }, {
                onProgress: (current, total, percentage) => {
                    // 模拟进度更新
                }
            });
        });

        // 测试 3: 动态添加任务
        const startTime3 = performance.now();
        await new Promise<void>((resolve) => {
            const async3 = task.createASync();
            
            // 先添加一半任务
            for (let i = 0; i < taskCount / 2; i++) {
                async3.add((next) => next(i));
            }
            
            async3.start(() => {
                const endTime3 = performance.now();
                Log.info(`动态添加任务: ${(endTime3 - startTime3).toFixed(2)}ms`);
                resolve();
            });
            
            // 运行后再添加另一半
            setTimeout(() => {
                for (let i = taskCount / 2; i < taskCount; i++) {
                    async3.add((next) => next(i));
                }
            }, 0);
        });
    }

    /**
     * 测试混合任务性能
     */
    public static async testAnyPerformance(taskCount: number = 100): Promise<void> {
        Log.info(`\n========== 测试 Any 性能 (${taskCount} 组任务) ==========`);

        const startTime = performance.now();
        await new Promise<void>((resolve) => {
            const any = task.createAny();
            
            for (let i = 0; i < taskCount; i++) {
                if (i % 3 === 0) {
                    // 每 3 个任务，插入一组并行任务
                    any.add([
                        (next) => next(i),
                        (next) => next(i + 1),
                        (next) => next(i + 2)
                    ]);
                } else {
                    // 顺序任务
                    any.add((next) => next(i));
                }
            }
            
            any.start(() => {
                const endTime = performance.now();
                Log.info(`混合任务执行时间: ${(endTime - startTime).toFixed(2)}ms`);
                any.dispose();
                resolve();
            });
        });
    }

    /**
     * 测试重试机制性能
     */
    public static async testRetryPerformance(): Promise<void> {
        Log.info(`\n========== 测试重试机制性能 ==========`);

        let retryCount = 0;
        const maxRetries = 100;
        
        const startTime = performance.now();
        await new Promise<void>((resolve) => {
            task.execute((retry) => {
                retryCount++;
                
                if (retryCount < maxRetries) {
                    retry(0); // 立即重试
                } else {
                    const endTime = performance.now();
                    Log.info(`重试 ${maxRetries} 次耗时: ${(endTime - startTime).toFixed(2)}ms`);
                    Log.info(`平均每次重试: ${((endTime - startTime) / maxRetries).toFixed(3)}ms`);
                    resolve();
                }
            });
        });
    }

    /**
     * Try-Catch 性能对比测试
     */
    public static testTryCatchImpact(): void {
        Log.info(`\n========== Try-Catch 性能影响测试 ==========`);

        const iterations = 10000000;

        // 测试 1: 无 try-catch
        let sum1 = 0;
        const startTime1 = performance.now();
        for (let i = 0; i < iterations; i++) {
            sum1 += i;
        }
        const endTime1 = performance.now();
        Log.info(`无 try-catch (${iterations} 次迭代): ${(endTime1 - startTime1).toFixed(2)}ms`);

        // 测试 2: 有 try-catch（不抛出异常）
        let sum2 = 0;
        const startTime2 = performance.now();
        try {
            for (let i = 0; i < iterations; i++) {
                sum2 += i;
            }
        } catch (e) {
            // 不会执行
        }
        const endTime2 = performance.now();
        Log.info(`有 try-catch (${iterations} 次迭代): ${(endTime2 - startTime2).toFixed(2)}ms`);

        // 测试 3: 回调函数 try-catch
        const callback = () => { };
        const startTime3 = performance.now();
        for (let i = 0; i < iterations; i++) {
            try {
                callback();
            } catch (e) {
                // 不会执行
            }
        }
        const endTime3 = performance.now();
        Log.info(`回调 try-catch (${iterations} 次迭代): ${(endTime3 - startTime3).toFixed(2)}ms`);

        // 测试 4: 无 try-catch 的回调
        const startTime4 = performance.now();
        for (let i = 0; i < iterations; i++) {
            callback();
        }
        const endTime4 = performance.now();
        Log.info(`回调无 try-catch (${iterations} 次迭代): ${(endTime4 - startTime4).toFixed(2)}ms`);

        // 计算性能差异
        const diff1 = ((endTime2 - startTime2) / (endTime1 - startTime1) - 1) * 100;
        const diff2 = ((endTime3 - startTime3) / (endTime4 - startTime4) - 1) * 100;
        Log.info(`\n性能影响：`);
        Log.info(`循环中的 try-catch: ${diff1.toFixed(2)}%`);
        Log.info(`回调中的 try-catch: ${diff2.toFixed(2)}%`);
    }

    /**
     * 运行所有测试
     */
    public static async runAll(): Promise<void> {
        Log.info('========================================');
        Log.info('       Task 系统性能测试开始');
        Log.info('========================================');

        // Try-Catch 性能影响测试
        this.testTryCatchImpact();

        // 任务队列性能测试
        await this.testSyncPerformance(1000);
        await this.testASyncPerformance(1000);
        await this.testAnyPerformance(100);
        await this.testRetryPerformance();

        Log.info('\n========================================');
        Log.info('       Task 系统性能测试完成');
        Log.info('========================================');
    }
}

/**
 * 导出测试工具
 */
export default PerformanceTest;

/**
 * 使用示例：
 * 
 * ```typescript
 * import PerformanceTest from './task_performance_test';
 * 
 * // 运行所有测试
 * PerformanceTest.runAll();
 * 
 * // 或单独测试
 * PerformanceTest.testSyncPerformance(1000);
 * PerformanceTest.testTryCatchImpact();
 * ```
 */

